<template>
    <div class="calendar no-select">
        <div class="header">
            <a-icon type="left" @click="prev"/>
            <div class="current-month">{{currentMonth}}</div>
            <a-icon type="right" @click="next()"/>
        </div>
        <div class="calendar-table">
            <table border="0" cellpadding="0" cellspacing="0"
                   :class="{'is-between': isBetween}">
                <thead>
                <tr>
                    <th v-for="item in weeks">{{item}}</th>
                </tr>
                </thead>
                <tbody @mouseover="mouseOver" @mouseout="mouseOut">
                <tr v-for="item in dateArr">
                    <td v-for="data in item">
                        <span v-html="data" v-if="isNumber(data) && !isToday(data) && !isBeforeToday(data)" class="active-period"></span>
                        <span v-html="data" v-else-if="isNumber(data) && isBeforeToday(data)" class="active-period time-grey"></span>
                        <span v-else-if="isNumber(data) && isToday(data)" class="active-period">今天</span>
                    </td>
                </tr>
                </tbody>
            </table>
        </div>
        <div class="calendar-footer">
            <p><span class="red">注：</span> 鼠标移入显示具体周期</p>
        </div>
    </div>
</template>

<script>
    import moment from 'moment';

    export default {
        name: "calendar.vue",
        props: [
            'cycleDate',
        ],
        data() {
            return {
                year: '',
                month: '',
                day: '',
                dateArr: [],
                weeks: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
                activeDay: {
                    firstDay: '',
                    lastDay: '',
                },
            }
        },
        async created() {
            this.year = moment().get('year');
            this.month = moment().get('month') + 1;
            this.day = moment().get('date');

            await this.getCalendar();
        },
        updated() {
            let innerMonthAll = Array.from(document.querySelectorAll('.active-period'));
            this.$emit('gaveAll', [innerMonthAll, this.month, this.year])
        },
        computed: {
            currentMonth() {
                return this.year + '年' + this.month + '月';
            },
            isBetween() {
                let activeDayArr = this.cycleDate.cycle_day.split('-');
                let firstDay = activeDayArr[0];
                let lastDay = activeDayArr[1];

                let start = moment(firstDay, 'YYYY年MM月').valueOf();
                let end = moment(lastDay, 'YYYY年MM月').valueOf();

                let current = moment(this.year + '年' + this.month + '月', 'YYYY年MM月').valueOf();

                return current >= start && current <= end
            }
        },
        methods: {
            moment,
            isToday(date) {
                return (this.year + '-' + this.month + '-' + date) === moment().format('YYYY-M-D')
            },
            isBeforeToday(date) {
                return moment(this.year + '-' + this.month + '-' + date, 'YYYY-M-D').valueOf() <
                    moment(moment().format('YYYY-M-D'), 'YYYY-M-D').valueOf()
            },
            isNumber(num) {
                return typeof num === 'number'
            },
            isLeapYear() {
                const year = this.year;
                if (year % 4 === 0 && year % 100 > 0) {
                    return true;
                } else if (year % 400 === 0 && year % 3200 > 0) {
                    return true;
                } else {
                    return false;
                }
            },
            getMonthLength() {
                const month = this.month;
                if (month === 2) {
                    if (this.isLeapYear()) {
                        return 29;
                    } else {
                        return 28;
                    }
                } else {
                    if (month < 8) {
                        if (month % 2 > 0) {
                            return 31;
                        } else {
                            return 30;
                        }
                    } else {
                        if (month % 2 > 0) {
                            return 30;
                        } else {
                            return 31;
                        }
                    }
                }
            },
            getCalendar() {
                let len = this.getMonthLength();
                let arr = [];
                let firstDate = new Date(this.year, this.month - 1, 1);
                let monthLastDay = new Date(this.year, this.month - 1, 0);
                let firstWeekDay = firstDate.getDay() === 0 ? 7 : firstDate.getDay();
                let tem = 1;
                let nextMonthDay = 0;
                let count = Math.ceil((firstWeekDay + len - 1) / 7);
                for (let i = 0; i < count; i++) {
                    arr[i] = [];
                    for (let j = 0; j < 7; j++) {
                        tem++;
                        if (tem - firstWeekDay > 0 && tem - firstWeekDay <= len) {
                            arr[i][j] = tem - firstWeekDay;
                        } else if (tem - firstWeekDay <= 0) {
                            arr[i][j] = `<span style="color: #434B66"> ${monthLastDay.getDate() + tem - firstWeekDay} </span>`;
                        } else if (tem - firstWeekDay > len) {
                            arr[i][j] = `<span style="color: #434B66"> ${++nextMonthDay} </span>`;
                        }
                    }
                }
                this.dateArr = arr;
            },
            prev() {
                if (this.month === 1) {
                    this.year--;
                    this.month = 12;
                } else {
                    this.month--;
                }
                this.getCalendar();
                let spans = document.querySelector('.calendar-table table').querySelectorAll('span');
                spans.forEach(val => {
                    this.clearBackground(val)
                })
            },
            next() {
                if (this.month === 12) {
                    this.year++;
                    this.month = 1;
                } else {
                    this.month++;
                }
                this.getCalendar();
                let spans = document.querySelector('.calendar-table table').querySelectorAll('span');
                spans.forEach(val => {
                    this.clearBackground(val)
                })
            },
            clearBackground(element) {
                element.setAttribute('title', '');
                element.style.background = '';
                element.style.borderRadius = 0
            },
            mouseOver(e) {
                let that = e.target;
                let activePeriods = document.querySelectorAll('.active-period');
                if (that.title !== '') {
                    activePeriods.forEach(item => {
                        if (item.title === that.title) {
                            item.style.background = '#1890FF'
                        }
                    })
                }
            },
            mouseOut(e) {
                let that = e.target;
                let activePeriods = document.querySelectorAll('.active-period');
                if (that.title !== '') {
                    activePeriods.forEach(item => {
                        if (item.title === that.title) {
                            item.style.background = '#293B4E'
                        }
                    })
                }
            }
        }
    }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
    @import "../assets/scss/mixin";

    .no-select {
        -webkit-touch-callout: none;
        -webkit-user-select: none;
        -khtml-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
    }

    .calendar {
        width: 100%;

        .header {
            @include fj();
            align-items: center;
            padding: 10px 60px;
            border-top: 1px solid #1A1C21;
            border-left: 1px solid #1A1C21;
            border-right: 1px solid #1A1C21;
            background-color: #252834;

            & > .anticon {
                font-size: 18px;
                cursor: pointer;
            }

            .current-month {
                font-weight: 600;
                font-size: 16px;
            }
        }

        .calendar-table {
            border-top: 1px solid #1A1C21;
            border-left: 1px solid #1A1C21;
            border-right: 1px solid #1A1C21;
            padding-left: 60px;
            padding-right: 60px;

            & > table {
                background-color: #292C35;
                width: 100%;

                thead {
                    th {
                        text-align: center;
                        padding: 20px;
                    }
                }

                tbody {
                    td {
                        text-align: center;
                        height: 50px;
                    }
                    .active-period {
                        @include transition(all, 300ms, cubic-bezier(0.645, 0.045, 0.355, 1));
                    }
                    .time-grey {
                        color: #434B66;
                    }
                }

                &.is-between {
                    .active-period {
                        display: block;
                        line-height: 25px;
                    }
                }
            }
        }

        .calendar-footer {
            padding-top: 15px;
            padding-bottom: 15px;
            padding-left: 60px;
            border: 1px solid #1A1C21;
            .red {
                color: #FF5151;
            }
        }
    }
</style>